package com.itlaobing.demo.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Classname ServletContextListener
 * @Description TODO()
 * @Date 2020/11/13 0013 10:21
 * @Author by Administrator
 * @Version v1.0
 */
@WebListener
public class MyServletContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        // 初始化(创建, 服务器启动)
        ServletContext context = servletContextEvent.getServletContext();
        // 在线人数
        context.setAttribute("onlineNum", 0);
        // 在线用户, 放到 list 集合中
        context.setAttribute("onlineUsers", new ConcurrentHashMap<String, HttpSession>());
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        // 销毁（服务器停止）
        ServletContext context = servletContextEvent.getServletContext();
        context.removeAttribute("onlineNum");
    }
}
